<template>
    <el-form-item label="所属项目：">
        <el-select v-model="that.sysRodId"
                   @change="pagingQueryFile()">
            <el-option v-for="item in that.localdata"
                       :key="item.value"
                       :label="item.text"
                       :value="item.value"/>
        </el-select>
    </el-form-item>
  <!--    <el-form :inline="true" :model="formInline" class="demo-form-inline">-->
  <!--        <el-form-item label="时间:">-->
  <!--            <el-date-picker-->
  <!--                    v-model="formInline.dateValue"-->
  <!--                    type="datetimerange"-->
  <!--                    range-separator="To"-->
  <!--                    start-placeholder="Start date"-->
  <!--                    end-placeholder="End date"-->
  <!--                    value-format="YYYYMMDDhhmmss"-->
  <!--            />-->
  <!--        </el-form-item>-->
  <!--        <el-form-item>-->
  <!--            <el-button type="primary" @click="onSubmit">查询</el-button>-->
  <!--        </el-form-item>-->
  <!--    </el-form>-->
    <el-table :data="that.tableData" style="width: 100%">
        <el-table-column type="index" width="50"/>
        <el-table-column label="文件名" prop="fileId"/>
        <el-table-column label="时长" prop="duration"/>
        <el-table-column label="创建时间" prop="createTime"/>
        <el-table-column align="right">
            <template #header>
                <el-input v-model="search" size="small" placeholder="输入文件名筛选"/>
            </template>
            <template #default="scope">
                <el-button size="small"
                           type="primary"
                           @click="handlePreview(scope.row)">
                    预览
                </el-button>
                <el-button size="small"
                           @click="handleDownload(scope.row)">
                    下载
                </el-button>
                <el-button size="small"
                           type="danger"
                           @click="handleDelete(scope.row)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <br>
    <el-pagination
            v-model:current-page="that.pageNumber"
            v-model:page-size="that.pageSize"
            :page-sizes="[10, 20, 30, 40]"
            :small="false"
            :disabled="false"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="that.total"
            @size-change="pagingQueryFile()"
            @current-change="pagingQueryFile()"
    />

    <el-dialog v-model="dialogTableVisible"
               :title="previewSource.title"
               width="60%"
               @close="previewSource.title='无'">
        <div class="">
            <video v-if="previewSource.title==='视频'"
                   id="myVideo"
                   class="video-js"
                   controls
                   :autoplay="false"
                   preload="auto"
                   width="600"
                   height="400"
                   poster="../../assets/logo.svg">
                <source :src="previewSource.src" type="video/mp4">
            </video>
            <el-image v-else
                      :src="previewSource.src"
            />
        </div>
    </el-dialog>
</template>

<script setup>
import Video from 'video.js'
import 'video.js/dist/video-js.css'
import {computed, inject, onMounted, reactive, ref, watch} from 'vue'
import {ElMessage, ElMessageBox} from "element-plus";
import axios from "axios";

// 使用 inject 获取全局变量
const $host = inject('$host');
axios.defaults.baseURL = $host

const that = reactive({
    localdata: [{
        value: '001',
        text: "001"
    }, {
        value: '002',
        text: "002"
    }],
    sysRodId: 1,
    pageNumber: 1,
    pageSize: 20,
    total: 0,
    tableData: [],
    daterange: [],
})
// const onSubmit = () => {
//     console.log('submit!')
//     queryFilesParams.startTime = formInline.dateValue == null ? '20230101000000' : formInline.dateValue[0]
//     queryFilesParams.endTime = formInline.dateValue == null ? '20990101000000' : formInline.dateValue[1]
// }

const previewSource = reactive({
    src: '',
    cover: null,
    title: '视频',
})
const dialogTableVisible = ref(false)


const queryFilesParams = reactive({
    sysRodId: '001',
    startTime: '20230404000000',
    endTime: null,
    pageNumber: 0,
    pageSize: 50
})
onMounted(() => {
    console.log('mounted...');
    // 获取所有杆
    axios({
        method: 'GET',
        url: '/rod',
    }).then(({data}) => {
        that.localdata = data.data.map(item => {
            return {
                value: item.id,
                text: item.projectName
            }
        })
    })
    // 加载表格数据
    pagingQueryFile()
})

function pagingQueryFile() {
    axios({
        method: 'GET',
        url: '/cloud/file',
        params: {
            sysRodId: that.sysRodId,
            pageNumber: that.pageNumber - 1,
            pageSize: that.pageSize,
        }
    }).then(({data}) => {
        if (data.code === 200) {
            that.total = data.data.total
            that.tableData = data.data.data
        }
    })
}


function handlePreview(row) {
    console.log(row)
    axios({
        method: 'GET',
        url: '/cloud/file/' + row.fileId + '/preview',
        params: {
            sysRodId: that.sysRodId
        },
    }).then(({data}) => {
        if (row.duration > 0) {
            previewSource.title = '视频'
        } else {
            previewSource.title = '图片'
        }
        if (data.code === 200) {
            previewSource.src = data.data.urls[0]
            dialogTableVisible.value = true
        } else {
            ElMessage({
                message: data.msg,
                type: 'error',
            })
        }
    })
}

function handleDownload(row) {
    console.log(row)
    ElMessageBox.confirm('确认下载文件【' + row.fileId + '】吗？', '系统提示', {type: 'warning'})
        .then(() => {
            console.log('用户点击确定');
            downloadFile('/cloud/file/' + row.fileId + '/download?sysRodId=' + that.sysRodId,
                row.fileType === "0" ? "图像" + row.createTime + ".jpg" : "视频" + row.createTime +
                    ".mp4")
            downloadFile('/cloud/file/' + row.fileId + '/download-attach?sysRodId=' + that.sysRodId,
                row.fileType === "0" ? "图像描述" + row.createTime + ".txt" : "视频描述" + row.createTime +
                    ".txt")
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: 'Download canceled',
            })
        })
}

function downloadFile(url, fileName) {
    // uni.showLoading({
    //     title: '下载中'
    // });
    const downloadTask = axios({
        method: 'GET',
        url: url,
    }).then((res) => {
        if (res.statusCode === 200) {
            console.log('下载成功');
            // uni.hideLoading()
            // uni.showModal({
            //     title: '提示',
            //     content: '下载成功',
            //     showCancel: false
            // });
            console.log(res.tempFilePath)
            var oA = document.createElement("a");
            oA.download = ''; // 设置下载的文件名，默认是'下载'
            oA.href = res.tempFilePath;
            document.body.appendChild(oA);
            oA.download = fileName;
            oA.click();
            oA.remove(); // 下载之后把创建的元素删除
        }
    })

    // downloadTask.onProgressUpdate((res) => {
    //     console.log('下载进度' + res.progress);
    //     console.log('已经下载的数据长度' + res.totalBytesWritten);
    //     console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
    //
    //     // // 满足测试条件，取消下载任务。
    //     // if (res.progress > 50) {
    //     // 	downloadTask.abort();
    //     // }
    // });
}

function handleDelete(row) {
    console.log(row)
    ElMessageBox.confirm('确认删除文件【' + row.fileId + '】吗？', '系统提示', {type: 'warning'})
        .then(() => {
            axios({
                method: 'DELETE',
                url: '/cloud/file/' + row.fileId,
                params: {
                    sysRodId: that.sysRodId
                },
            }).then(({data}) => {
                if (data.code === 200) {
                    ElMessage({
                        message: data.msg,
                        type: 'success',
                    })
                    pagingQueryFile()
                } else {
                    ElMessage({
                        message: data.msg,
                        type: 'error',
                    })
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: 'Delete canceled',
            })
        })
}
</script>
